﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using nwrole.Module.lib;

namespace nwrole.ModuleService
{
    public class ModuleFileLogger : IModuleLogger
    {
        private Object _logLock = new Object();

        private LogLevel _logLevel;

        public ModuleFileLogger(LogLevel logLevel = LogLevel.Error)
        {
            _logLevel = logLevel;
        }

        /*public void Log(LogLevel level, string msg, Exception ex)
        {
            lock (_logLock)
            {
                if (ex == null)
                    WriteLog(msg);
                else
                    WriteLog(msg + " Exception: " + ex);
            }
        }*/

        public void Log(LogLevel level, string msg)
        {
            if(level <= _logLevel)
            {
                lock (_logLock)
                {
                    WriteLog(level.ToString() + ": " + msg);
                }
            }
        }

        private static void WriteLog(string content)
        {
            try
            {
                string logDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "log/");
                if (!System.IO.Directory.Exists(logDir))
                    System.IO.Directory.CreateDirectory(logDir);

                DateTime now = DateTime.Now;

                System.IO.File.AppendAllText(logDir + "log " + now.ToString("yyyy-MM-dd") + ".txt", now.ToString("yyyy-MM-dd HH:mm:ss ") + content + "\r\n");
            }
            catch
            {
            }
        }
    }
}
